package com.lab.dag;

import com.lab.NoobChain;
import com.lab.forthreadpool.Block;
import com.lab.forthreadpool.Transaction;

public class DAGRunnable implements Runnable {

    private int A;
    private int B;
    private double val;

    public DAGRunnable(int a, int b, double val) {
        A = a;
        B = b;
        this.val = val;
    }

    @Override
    public void run() {
        Transaction transaction = null;
        long startTime = System.currentTimeMillis();
        NoobChain.startTime = Math.min(NoobChain.startTime, startTime);

        //钱包锁
        while (!NoobChain.tryGetLock(A, B)) ;
        NoobChain.wallets.get(A).getBalance();
        NoobChain.wallets.get(B).getBalance();

        System.out.println(A + " -> " + B + " " + val);

        //生成 A->B val 的交易类
        transaction = NoobChain.wallets.get(A).sendFunds(NoobChain.wallets.get(B).publicKey, val);
        if (!transaction.processTransaction()) {
            System.out.println("交易失败！");
        }
        //释放锁
        NoobChain.locks[A].unlock();
        NoobChain.locks[B].unlock();


        Block block = null;
        if (NoobChain.blockchain.size() != 0) {
            int n = NoobChain.blockchain.size();
            if (n >= 2)
                block = new Block(NoobChain.blockchain.get(n - 1).hash, NoobChain.blockchain.get(n - 2).hash);
            else
                block = new Block(NoobChain.blockchain.get(0).hash);
        } else {
            block = new Block(NoobChain.genesis.hash);
        }
        block.transactions.add(transaction);
        NoobChain.addBlock(block);
        long endTime = System.currentTimeMillis();
        NoobChain.endTime = Math.max(endTime, NoobChain.endTime);
    }
}
